﻿/*----------------------------------------------------------------
// Copyright (C) 2005 麦迪斯顿(北京)医疗科技发展有限公司
// 文件名：ApplicationContext.cs
// 文件功能描述：ApplicationContext
// 创建标识：顾伟伟-2012-04-14
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Text;
using Medicalsystem.Docare.Common.Principal;
using System.Net;
using System.Net.Sockets;
using Medicalsystem.Docare.Common.Container;

namespace Medicalsystem.Docare.Common
{
    /// <summary>
    /// 表示应用程序上下文的类
    /// </summary>
    public partial class AppContext
    {
        private static readonly AppContext _context = new AppContext();
        private Identity _identity = new Identity();
        private ServiceLocator _serviceLocator = new ServiceLocator();
        private string _clientIp = string.Empty;

        private AppContext()
        {
        }
        /// <summary>
        /// 服务端IP地址1
        /// </summary>
        public string ServerIP { get; set; }
        /// <summary>
        /// 获取或者设置应用程序的唯一ID
        /// </summary>
        public string ApplicationId { get; set; }
        /// <summary>
        /// 获取或者设置应用程序的名称
        /// </summary>
        public string ApplicationName { get; set; }
        /// <summary>
        /// 获取或者设置客户端IP地址，
        /// </summary>
        public string ClientIP
        {
            get
            {
                if (string.IsNullOrEmpty(_clientIp))
                    _clientIp = GetIpAddress();
                return _clientIp;
            }
            set
            {
                _clientIp = value;
            }
        }
        
        /// <summary>
        /// 获取当前唯一实例
        /// </summary>
        public static AppContext Current
        {
            get
            {
                return _context;
            }
        }
        /// <summary>
        /// 获取当前用户的身份标识
        /// </summary>
        public Identity UserIdentity 
        {
            get
            {
                return _identity;
            }
        }
        /// <summary>
        /// 获取应用程序上下文服务存储容器
        /// </summary>
        public ServiceLocator ServiceLocator
        {
            get
            {
                return _serviceLocator;
            }
        }
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        private string GetIpAddress()
        {
            var addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            foreach (var address in addressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    return  address.ToString();
                }
            }
            return string.Empty;
        }
    }
}
